#!/usr/bin/env ts-node

/**
 * Simple test example to verify basic functionality
 */

import {
  RabbitMQClient,
  createFunctionHandler,
} from '../src';

async function simpleTest(): Promise<void> {
  console.log('🧪 Simple RabbitMQ Test');
  console.log('=======================');

  // Create client with configuration from environment variables
  const client = RabbitMQClient.create({
    host: process.env.RABBITMQ_HOST || 'localhost',
    port: parseInt(process.env.RABBITMQ_PORT || '5672'),
    username: process.env.RABBITMQ_USERNAME || 'guest',
    password: process.env.RABBITMQ_PASSWORD || 'guest',
  });

  try {
    await client.initialize();
    console.log('✅ Client initialized successfully');

    // Test Work Queue
    console.log('\n📋 Testing Work Queue...');
    const workQueue = client.createWorkQueue('simple_test_queue');
    await workQueue.setupQueue();

    const handler = createFunctionHandler(async (data: any) => {
      console.log(`  ✅ Processed: ${JSON.stringify(data)}`);
      return { processed: true, timestamp: new Date().toISOString() };
    });

    await workQueue.startWorkers(handler, 1);
    console.log('✅ Worker started');

    // Send test messages
    for (let i = 1; i <= 3; i++) {
      await workQueue.sendTask({
        id: i,
        message: `Test message ${i}`,
        timestamp: new Date().toISOString(),
      });
      console.log(`📤 Sent message ${i}`);
    }

    // Wait for processing
    await new Promise(resolve => setTimeout(resolve, 3000));

    await workQueue.stopWorkers();
    console.log('✅ Workers stopped');

    // Test Pub/Sub
    console.log('\n📢 Testing Pub/Sub...');
    const pubsub = client.createPubSub('simple_test_exchange');
    await pubsub.setupExchange();

    const notificationHandler = createFunctionHandler(async (data: any) => {
      console.log(`  📬 Received: ${JSON.stringify(data)}`);
      return { received: true };
    });

    await pubsub.subscribe(notificationHandler, { queueName: 'simple_test_notifications' });
    console.log('✅ Subscribed to notifications');

    // Publish test messages
    for (let i = 1; i <= 3; i++) {
      await pubsub.publish({
        type: 'test_notification',
        id: i,
        message: `Notification ${i}`,
        timestamp: new Date().toISOString(),
      });
      console.log(`📤 Published notification ${i}`);
    }

    // Wait for processing
    await new Promise(resolve => setTimeout(resolve, 3000));

    await pubsub.stopAllSubscribers();
    console.log('✅ Subscribers stopped');

    console.log('\n🎉 All tests completed successfully!');

  } catch (error) {
    console.error('❌ Test failed:', error);
  } finally {
    await client.close();
    console.log('🔒 Client closed');
  }
}

// Run the test
if (require.main === module) {
  simpleTest().catch(console.error);
}

export { simpleTest };
